<template>
  <div class="block">
    <el-switch v-model="draggable" active-text="开启菜单编辑" inactive-text="关闭菜单编辑"></el-switch>

    <el-button @click="batchsve" v-if="draggable">批量保存</el-button>
    <el-button @click="batchremove(data)" v-if="showcheckbox">批量删除</el-button>

    <el-tree
      ref="mentTree"
      :data="data"
      :show-checkbox="showcheckbox"
      :props="defaultProps"
      :expand-on-click-node="false"
      :default-expanded-keys="expandedkey"
      @node-drop="handleDrop"
      :draggable="draggable"
      :allow-drop="allowDrop"
      node-key="catId"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button v-if="node.level<=2" type="text" size="mini" @click="() => append(data)">添加</el-button>
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >删除</el-button>
          <el-button type="text" size="mini" @click="() => info(node, data)">修改</el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="30%">
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="category.productUnit" autocomplete="off"></el-input>
        </el-form-item>
        <!-- <el-form-item label="活动区域">
          <el-select v-model="category.region" placeholder="请选择活动区域">
            <el-option
              v-for="item in form.region"
              :key="item.catId"
              :label="item.sort"
              :value="item.name"
            ></el-option>
          </el-select>
        </el-form-item>-->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="() =>this.category.catId == undefined ? addcategory() : update() "
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//<!-- :render-content="renderContent"> -->
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { treeDataTranslate } from "@/utils";
export default {
  //import引入的组件需要注入到对象中才能使用

  components: {},
  data() {
    const data = [];
    return {
      showcheckbox: true,
      pCid: 0,
      draggable: false,
      //修改排序存放
      updateNodes: [],
      //树形菜单属性
      //
      defaultProps: {
        children: "children",
        label: "name",
      },
      MaxLeevel: 0,
      title: "添加分类",
      category: {
        catId: "",
        name: "",
        parentCid: "",
        catLevel: "",
        showStatus: "",
        sort: 0,
        icon: "",
        productUnit: "",
        productCount: 0,
      },
      dialogVisible: false,
      expandedkey: [],
      data: JSON.parse(JSON.stringify(data)),
      data: JSON.parse(JSON.stringify(data)),
    };
  },

  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合

  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getMenus();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {},
  //生命周期 - 创建之前
  beforeMount() {},
  //生命周期 - 挂载之前
  beforeUpdate() {},
  //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
  methods: {
    //判断能否被拖拽
    allowDrop(draggingNode, dropNode, type) {
      //第一种方法 较简单 但不保证 父节点是否被拖拽 到子节点
      // if (dropNode.data.catLevel <=3) {
      //   return type !== "inner";
      // } else {
      //   return true;
      // }
      //第二种方法 适用于所有分类层级
      this.countNodeLevel(draggingNode.data);
      let deep = this.MaxLeevel - draggingNode.data.catLevel + 1;
      console.log("深度：", deep);
      // console.log((deep + dropNode.level) <= 3)
      console.log(deep + dropNode.parent.level <= 3);
      if (type == "inner") {
        console.log(
          `this.MaxLeevel: ${this.MaxLeevel}, draggingNode.data.catLevel:${draggingNode.data.catLevel}`
        );
        return deep + dropNode.level <= 3;
      } else {
        return deep + dropNode.parent.level <= 3;
      }
    },
    countNodeLevel(node) {
      if (node.children != null && node.children.length > 0) {
        for (let i = 0; i < node.children.length; i++) {
          if (node.children[i].catLevel > this.MaxLeevel) {
            this.MaxLeevel = node.children[i].catLevel;
          }
          this.countNodeLevel(node.children[i]);
        }
      }
    },
    batchsve() {
      this.$http({
        url: this.$http.adornUrl("/product/category/update/sort"),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false),
      }).then(({ data }) => {
        if (data.code === 0 && data != null) {
          this.$message({
            message: "操作成功",
            type: "success",
          });
        } else {
          this.$message({
            message: "菜单修改失败",
            type: "error",
          });
        }
      });
      setTimeout(() => {
        this.getMenus();
        this.expandedkey = [this.pCid];
      }, 500);

      console.log("执行刷新");
      //执行 初始化
      this.updateNodes = [];
      this.MaxLeevel = 0;
      console.log("初始化完毕");
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log("handleDrop ", draggingNode, dropNode, dropType);
      //当前兄弟节点排序
      let siblings = null;
      //当前节点最新的父节点id
      // let pCid = 0;
      //需要判断 该节点是以什么方式 进入此节点
      if (dropType == "before" || dropType == "after") {
        console.log(dropType);
        this.pCid =
          dropNode.parent.data.catId == undefined
            ? 0
            : dropNode.parent.data.catId;
        //获取兄弟节点的排序
        siblings = dropNode.parent.childNodes;
      } else {
        console.log("inner", dropType);
        this.pCid = dropNode.data.catId;
        siblings = dropNode.childNodes;
      }

      //当前拖拽节点的顺序
      //便利这些兄弟
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId == draggingNode.data.catId) {
          //修改兄弟的位置,在修改自己父id的值
          //当此节点的层级出现 变化
          let catLevel = draggingNode.level;
          console.log("当前节点层级", catLevel);
          if (siblings[i].level != draggingNode.level) {
            catLevel = siblings[i].level;
            console.log("修改层级之后", catLevel);
            //他子节点的层级
            this.updateChildNodeLevel(siblings[i]);
          }
          this.updateNodes.push({
            catId: siblings[i].data.catId,
            sort: i,
            parentCid: this.pCid,
            catLevel: catLevel,
          });
        } else {
          //修改兄弟的位置
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
        }
      }

      //当前拖拽节点的最新层级
      console.log(this.updateNodes);
    },
    updateChildNodeLevel(node) {
      if (node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          var cnode = node.childNodes[i].data;
          this.updateNodes.push({
            catId: cnode.catId,
            catLevel: node.childNodes[i].level,
          });
          this.updateChildNodeLevel(node.childNodes[i]);
        }
      }
    },
    append(data) {
      //初始化 分类列表
      this.category = {};
      console.log("append", data);
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
      this.category.showStatus = 1;
      this.category.sort = 0;
      this.title = "添加分类";
      this.dialogVisible = true;
    },

    remove(node, data) {
      var ids = [data.catId];
      console.log(data.name);
      this.$confirm(`是否删除【${data.name}】菜单?`, "提示", {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消删除",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getMenus();
                  this.expandedkey = [node.parent.data.catId];
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });

      console.log("remove", node, data);
    },
    getMenus() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        this.data = data.data;
      });
    },
    //添加三级分类
    addcategory() {
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: "操作成功",
            type: "success",
            duration: 1500,
          });
        } else {
          this.$message.error(data.msg);
        }
      });
      //关闭窗口
      this.dialogVisible = false;
      this.getMenus();
      this.expandedkey = [this.category.parentCid];
    },
    info(node, data) {
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.title = "修改分类";
          this.category = data.category;
          this.dialogVisible = true;
          console.log(this.category);
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    //批量删除节点
    batchremove(data) {
      let checkeNodes = this.$refs.mentTree.getCheckedNodes();
      let catIds = [];
      for (let i = 0; i < checkeNodes.length; i++) {
        catIds.push(checkeNodes[i].catId);
      }
      console.log("数组", catIds);
      //  this.$refs.mentTree.getCheckedNodes();
      console.log("被选中的节点：", checkeNodes);
      this.$confirm(
        `是否删除【${checkeNodes[0].name}】菜单及菜单下的所选内容内容吗?`,
        "提示",
        {
          confirmButtonText: "确定删除",
          cancelButtonText: "取消删除",
          type: "warning",
        }
      )
        .then(() => {
          this.$http({
            url: this.$http.adornUrl(`/product/category/delete`),
            method: "post",
            data: this.$http.adornData(catIds, false),
          }).then(({data}) => {
            if (data.code == 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
              });
         this.getMenus();
            }
          });
        })
        .catch(() => {
          this.$message({
            message: "操作已取消",
            type: "warning",
            duration: 1500,
          });
        });
    },
    update() {
      this.$http({
        url: this.$http.adornUrl(`/product/category/update`),
        method: "post",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: "操作成功",
            type: "success",
            duration: 1500,
          });
        } else {
          this.$message.error(data.msg);
        }
        this.dialogVisible = false;
        this.getMenus();
        this.expandedkey = [this.category.parentCid];
      });
    },
  },
};
</script>
<style scoped>
/* //@import url(); 引入公共css类 */

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>